package route

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/time/rate"
	controllers "mytest/common-admin/controller"
	"mytest/util"
	"net/http"
	"time"
)

func LoadAdminRoutes(r *gin.Engine) {
	var logincontroller controllers.LoginController

	r.GET("/sess/set", func(c *gin.Context) {
		l := util.NewLimiter(rate.Every(1*time.Second), 1, c.ClientIP())

		if !l.Allow() {
			c.String(http.StatusOK, "您的访问过于频繁")
			return
		}
		store, err := util.SessionStart(c.Writer, c.Request)
		if err != nil {
			fmt.Fprint(c.Writer, err)
			return
		}
		key := c.DefaultQuery("key", "")
		val := c.DefaultQuery("val", "")
		if key != "" && val != "" {
			store.Set(key, val)
		} else {
			store.Set("foo", "bar")
		}
		err = store.Save()
		if err != nil {
			fmt.Fprint(c.Writer, err)
			return
		}
		c.String(http.StatusOK, "session set")
	})
	r.GET("/sess/get", func(c *gin.Context) {
		key := c.DefaultQuery("key", "")
		if key == "" {
			key = "foo"
		}
		store, err := util.SessionStart(c.Writer, c.Request)
		if err != nil {
			fmt.Fprint(c.Writer, err)
			return
		}

		val, ok := store.Get(key)
		if ok {
			fmt.Fprintf(c.Writer, "key:%s", val)
			return
		}
		fmt.Fprint(c.Writer, "does not exist")
		c.String(http.StatusOK, "session get")
	})

	r.GET("/captcha", logincontroller.Captcha)
	r.GET("/captcha/verify", logincontroller.VerifyCaptcha)

	r.GET("/login", logincontroller.Index)
	r.POST("/login", logincontroller.Index)

	admin := r.Group("admin")
	{
		admin.GET("/", func(c *gin.Context) {
			c.HTML(http.StatusOK, "index/index.html", gin.H{"title": "layuiadmin", "version": "1.0.0"})
		})
		admin.GET("/admin", func(c *gin.Context) {
			c.HTML(http.StatusOK, "admin/index.html", gin.H{"title": "layuiadmin", "version": "1.0.0"})
		})
		admin.GET("/auth", func(c *gin.Context) {
			c.HTML(http.StatusOK, "auth/index.html", gin.H{"title": "layuiadmin", "version": "1.0.0"})
		})
		admin.GET("/config", func(c *gin.Context) {
			c.HTML(http.StatusOK, "config/index.html", gin.H{"title": "layuiadmin", "version": "1.0.0"})
		})
		admin.GET("/log", func(c *gin.Context) {
			c.HTML(http.StatusOK, "log/index.html", gin.H{"title": "layuiadmin", "version": "1.0.0"})
		})
		admin.GET("/menu", func(c *gin.Context) {
			c.HTML(http.StatusOK, "menu/index.html", gin.H{"title": "layuiadmin", "version": "1.0.0"})
		})
		admin.GET("/quick", func(c *gin.Context) {
			c.HTML(http.StatusOK, "quick/index.html", gin.H{"title": "layuiadmin", "version": "1.0.0"})
		})

	}

}
